package com.gmall.data.utils;

import com.gmall.data.pojo.LogBean;
import com.gmall.data.pojo.RuleAtomicParam;
import org.apache.commons.lang3.time.DateUtils;

import java.util.*;


/**
 * 用于判断一个事件和一个规则中的条件是否匹配
 */
public class RuleUtil {

    public static boolean logBeanMathParam(LogBean logBean, RuleAtomicParam param) {
        // 如果传入的一个事件id与参数中的事件id相同，才开始进行属性判断
        if (logBean.getEventId().equals(param.getEventId())) {

            // 取出待判断事件中的属性
            Map<String, String> properties = logBean.getProperties();

            // 取出条件中的事件属性
            HashMap<String, String> paramProperties = param.getProperties();

            // 对条件属性进行遍历，判断这个事件的属性值是否匹配
            for (Map.Entry<String, String> entry : paramProperties.entrySet()) {
                // 遍历条件中的每个属性及值
                if (!entry.getValue().equals(properties.get(entry.getKey())))
                    return false;
            }
            return true;
        }
        return false;
    }

    public static String getBufferKey(String deviceId,RuleAtomicParam atomicParam){
        // deviceId-EVENT-p1-v1-p2-v2
        StringBuffer sb = new StringBuffer();
        sb.append(deviceId).append("-").append(atomicParam.getEventId());

        HashMap<String, String> properties = atomicParam.getProperties();
        Set<Map.Entry<String, String>> entries = properties.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            sb.append("-").append(entry.getKey()).append("-").append(entry.getValue());
        }

        return sb.toString();
    }

    public static String getBufferKey(String deviceId, List<RuleAtomicParam> paramList){
        // deviceId-EVENT1-p1-v1-p2-v2-EVENT2-p1-v1-p2-v2
        StringBuffer sb = new StringBuffer();
        sb.append(deviceId);

        for (RuleAtomicParam ruleAtomicParam : paramList) {
            sb.append("-").append(ruleAtomicParam.getEventId());
            HashMap<String, String> properties = ruleAtomicParam.getProperties();
            Set<Map.Entry<String, String>> entries = properties.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                sb.append("-").append(entry.getKey()).append("-").append(entry.getValue());
            }
        }

        return sb.toString();
    }

    public static long getQuerySplit(){
        return DateUtils.addHours(DateUtils.ceiling(new Date(), Calendar.HOUR), -2).getTime();
    }
}
